﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace XNAGraffiti
{
    public class DelegateDispatcher
    {
        private Queue<KeyValuePair<Delegate, ManualResetEvent>> m_delegateQueue = new Queue<KeyValuePair<Delegate, ManualResetEvent>>();

        public void Invoke(Delegate method)
        {
            var del = new KeyValuePair<Delegate, ManualResetEvent>(method, new ManualResetEvent(false));
            lock (m_delegateQueue)
                m_delegateQueue.Enqueue(del);

            del.Value.WaitOne();
        }

        public void BeginInvoke(Delegate method)
        {
            lock (m_delegateQueue)
            {
                var del = new KeyValuePair<Delegate, ManualResetEvent>(method, null);
                m_delegateQueue.Enqueue(del);
            }
        }

        internal void ProcessDelegateQueue()
        {
            var delegateQueue = new Queue<KeyValuePair<Delegate, ManualResetEvent>>();

            lock (m_delegateQueue)
                while (m_delegateQueue.Count > 0)
                    delegateQueue.Enqueue(m_delegateQueue.Dequeue());

            while (delegateQueue.Count > 0)
            {
                var del = delegateQueue.Dequeue();

                try
                {
                    del.Key.DynamicInvoke(null);
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    if (del.Value != null)
                    {
                        del.Value.Set();
                        del.Value.Close();
                    }
                }
            }
        }
    }
}
